package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"main/api/request"
	"main/global"
	"main/internal/dao"
	"main/internal/model"
	"main/internal/utils"
	"main/pkg"
	"net/http"
	"time"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.GetUserByMobile(req.Mobile)
	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户已存在",
			"data": nil,
		})
		return
	}
	user = model.User{
		Mobile:   req.Mobile,
		Password: utils.Md5(req.Password),
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "数据库插入失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": user,
	})
}

func LoginUser(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.GetUserByMobile(req.Mobile)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	user = dao.GetUserByMobileAndPassword(user.Mobile, req.Password)
	token, _ := pkg.NewJWT(global.JWT_SECRET_KEY).CreateToken(pkg.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": token,
	})
}

func LogoutUser(c *gin.Context) {

}
